package demo.netty.netty.udp;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelOption;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.DatagramPacket;
import io.netty.channel.socket.nio.NioDatagramChannel;

import java.net.InetSocketAddress;
import java.nio.charset.StandardCharsets;

public class ChineseProverbClient {


    public static void main(String[] args) {
        new ChineseProverbClient().run(8080);
    }

    public void run(int port) {
        NioEventLoopGroup workGroup = new NioEventLoopGroup();
        try {
            Bootstrap bootstrap = new Bootstrap();
            bootstrap
                .group(workGroup)
                .channel(NioDatagramChannel.class)
                //设置Socket参数支持广播
                .option(ChannelOption.SO_BROADCAST, true)
                .handler(new ChineseProverbHandler());
            Channel channel = bootstrap.bind(0).sync().channel();
            //向网段内所有机器广播UDP消息
            channel.writeAndFlush(new DatagramPacket(Unpooled.copiedBuffer("谚语字典查询?", StandardCharsets.UTF_8),
                                                     new InetSocketAddress("255.255.255.255", port))).sync();
            //等待15秒用于接受返回数据，然后退出
            if (!channel.closeFuture().await(15000)) {
                System.out.println("查询超时!");
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            workGroup.shutdownGracefully();
        }
    }


    public static class ChineseProverbHandler extends SimpleChannelInboundHandler<DatagramPacket> {

        @Override
        protected void channelRead0(ChannelHandlerContext ctx, DatagramPacket msg) throws Exception {
            //将内容转换为字符串
            String response = msg.content().toString(StandardCharsets.UTF_8);
            if (response.startsWith("谚语查询结果：")) {
                System.out.println(response);
                ctx.close();
            }
        }
    }


}
